appCtrl.controller('OrderCtrl', function($scope, $state, UtilsService) {
  if (!UtilsService.isLogin()) {
    $state.go('login');
    return;
  }

  if (!UtilsService.isDistExist()) {
    $state.go('district.list');
    return;
  }
})


.controller('OrderListCtrl', function($scope, $rootScope, $ionicHistory, $ionicPopup, $state, UtilsService, UserService, AddressService, OrderService) {
    if (UtilsService.isLogin()) {
      OrderService.get().$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $scope.orders = response.data.orders;
        }
      });
    }


    $scope.type = 0;
    $scope.statelist = ['0', '1', '2', '3', '4'];
    // type 0--已发货|1--已付款|2--已完成(评价）|3--待退货|4--已退货
    $scope.changeShow = function(type) {
      $scope.type = type;
      switch (type) {
        case 0:
          // all
          $scope.statelist = ['0', '1', '2', '3', '4'];
          break;
        case 1:
          // not over
          $scope.statelist = ['0', '3'];
          break;
        case 2:
          // over
          $scope.statelist = ['1', '2', '4'];
          break;
        default:
      }
    }

    $scope.toOrderDetail = function(order) {
      $state.transitionTo('order.detail', {
        id: order.order_id
      }, {
        reload: true
      });
    }

    $scope.addComment = function(order) {
      $state.transitionTo('order.comment', {
        id: order.order_id
      }, {
        reload: true
      });
    }

    $scope.backOrder = function(order) {
      var confirmPopup = $ionicPopup.confirm({
        title: '退货',
        template: '是否确认退货？',
        buttons: [{
          text: '取消'
        }, {
          text: '<b>确认</b>',
          type: 'button-assertive',
          onTap: function(e) {
            return true;
          }
        }]
      });
      confirmPopup.then(function(res) {
        if (res) {
          OrderService.changeStatus({
            id: order.order_id,
            status: 3
          }).$promise.then(function(response) {
            if (UtilsService.isResponseOk(response)) {
              order.status = '3';
            }
          })
        }
      });
    }
  })
  .controller('OrderChooselocCtrl', function($scope, $rootScope, $stateParams, $ionicHistory, $state, UtilsService, UserService, AddressService, OrderService) {
    $scope.goodslist = $rootScope.goodslist;
    // console.log($scope.goodslist);

    if(UtilsService.isLogin()){
      AddressService.getDefault().$promise.then(function (response) {
        if(UtilsService.isResponseOk(response)){
          $scope.loc = response.data.address;
        }
      })
    }

    $scope.$watch(function() {
      return $rootScope.loc;
    }, function(newValue, oldValue) {
      if (newValue == oldValue) {
        return;
      }

      $scope.loc = newValue;
    });

    // 计算和
    $scope.count = 0;
    $scope.sendprice = '6.0';
    for (var i in $scope.goodslist) {
      var goods = $scope.goodslist[i];

      $scope.count += parseInt(goods.num) * parseFloat(goods.cx_price || goods.kj_price);

      // 满9元包邮
      if(goods.tag == '1'){
        $scope.sendprice = '0.0';
      }
    }

    // 满9元包邮
    if($scope.count < 9){
      $scope.sendprice = '6.0';
    }

    $scope.selectLoc = function() {
      $rootScope.prevState = 'order.chooseloc';
      $state.transitionTo('mine.address.list', {}, {
        reload: true,
        notify: true,
        inherit: false
      });
    }

    $scope.goBack = function() {
      $ionicHistory.goBack();
    }

    $scope.addOrder = function() {
      if (!$scope.loc || !$scope.goodslist || $scope.goodslist.length < 1) {
        $rootScope.$broadcast('loading:showMessage', {
          message: '尚未选择地址'
        });
        return;
      }
      var order = {};
      order['loc'] = $scope.loc;
      order['products'] = $scope.goodslist;
      order['note'] = window.document.getElementById('note').value;
      order['district'] = UtilsService.getDist();

      // console.log($scope.note);
      // console.log(angular.toJson(order));
      OrderService.save(order).$promise.then(function(response) {
        // console.lgo(response);
        if (UtilsService.isResponseOk(response)) {
          $rootScope.orderid = response.data.orderid;
          $state.transitionTo('order.success', {}, {
            reload: true,
            notify: true,
            inherit: false
          });
        }
      });
    }
  })
  .controller('OrderSuccessCtrl', function($scope, $rootScope) {

    $scope.orderid = $rootScope.orderid;
  })
  .controller('OrderDetailCtrl', function($scope, $rootScope, $state, $stateParams, $ionicPopup, UtilsService, UserService, AddressService, OrderService) {

    if (!$stateParams.id) {
      $state.go('dash.home');
      $rootScope.$broadcast('loading:hide');
      $rootScope.loadCount = 0;
      return;
    }
    OrderService.get({
      id: $stateParams.id
    }).$promise.then(function(response) {
      if (UtilsService.isResponseOk(response)) {
        $scope.order = response.data.order;
      }
    });


    $scope.backOrder = function() {
      var confirmPopup = $ionicPopup.confirm({
        title: '退货',
        template: '是否确认退货？',
        buttons: [{
          text: '取消'
        }, {
          text: '<b>确认</b>',
          type: 'button-assertive',
          onTap: function(e) {
            return true;
          }
        }]

      });
      confirmPopup.then(function(res) {
        if (res) {
          OrderService.changeStatus({
            id: $scope.order.order_id,
            status: 3
          }).$promise.then(function(response) {
            if (UtilsService.isResponseOk(response)) {
              $scope.order.status = '3';
            }
          })
        }
      });
    }


  })
  .controller('OrderCommentCtrl', function($scope, $rootScope, $stateParams, $ionicHistory, UtilsService, UserService, AddressService, OrderService) {

    OrderService.get({
      id: $stateParams.id
    }).$promise.then(function(response) {
      if (UtilsService.isResponseOk(response)) {
        $scope.order = response.data.order;
      }
    })

    $scope.goBack = function() {
      $ionicHistory.goBack();
    }

    // 添加评论
    $scope.addComment = function() {
      var order = {};
      order.comments = [];
      // 创建comments数组
      angular.forEach($scope.order.order_products, function(item) {
        var comment = {
          product_id: item.product_id,
          score: item.score,
          comment: item.comment
        };
        order.comments.push(comment);
      });

      OrderService.addComment({
        comments: order.comments,
        id: $stateParams.id
      }).$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $ionicHistory.goBack();
        }
      })
    }
  })
  .controller('OrderCartCtrl', function($scope, $rootScope, $state, UtilsService, UserService) {
    $scope.edit = false;

    // 选中商品
    $scope.goodschecked = [];
    $scope.checkAll = true;

    // 设置购物车内物品数量
    $scope.setNum = function(goods, num) {
      if(goods.xg_amount && parseInt(goods.xg_amount) < parseInt(goods.num) + num){
        // 限购返回
        return;
      }
      if ($scope.edit) {
        return;
      }
      var curnum = parseInt(goods.num) + parseInt(num);
      if (curnum <= 0) {
        if (!confirm('是否删除该商品')) {
          return;
        }
      }
      UserService.changeNumOfGoodsInCart({
        shopping_cart_id: goods.shopping_cart_id,
        num: curnum
      }).$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {

          if (curnum <= 0) {
            var key = goods.class3 + '_' + goods.sendtype;
            var i = $scope.cartproducts[key]['products'].indexOf(goods);
            var index = $scope.goodschecked.indexOf(goods);
            if (index >= 0) {
              $scope.goodschecked.splice(index, 1);
            }
            $scope.cartproducts[key]['products'].splice(i, 1);

            if ($scope.cartproducts[key]['products'].length == 0) {
              delete $scope.cartproducts[key];

              // var j = $scope.cartproducts.indexOf($scope.cartproducts[key]);
              //
              // $scope.cartproducts.splice(j, 1);
            }
          } else {
            goods.num = curnum;
          }
        }
      })
    }

    $scope.calculateAmount = function() {
      var count = 0;
      for (var i in $scope.cartproducts) {
        for (var j in $scope.cartproducts[i]['products']) {
          if ($scope.cartproducts[i] == undefined) {
            continue;
          }
          var goods = $scope.cartproducts[i]['products'][j];
          // console.log(goods);

          if (goods.isCheck) {
            count += parseInt(goods.num) * parseFloat(goods.cx_price || goods.kj_price);
          }
        }
      }

      return count.toFixed(1);
    }

    $scope.getsendpirce = function () {
      var count = $scope.calculateAmount()
      if(count == 0){
        return '0.0';
      }
      if(count < 9){
        return '6.0';
      }
      var result = false; // 判断是否有满9包邮的
      for (var i in $scope.goodschecked) {
        var goods = $scope.goodschecked[i];
        if(goods.tag == '1'){
          result = true;
          break;
        }
      }

      return result? '0.0' : '6.0';
    }

    // 购物车全选中
    $scope.$watch('checkAll', function(newValue, oldValue) {
      if (newValue == oldValue) {
        return;
      }
      $scope.goodschecked = [];

      // 删除
      if (!newValue) {
        // 全不选
        for (var i in $scope.cartproducts) {
          for (var j in $scope.cartproducts[i]['products']) {
            $scope.cartproducts[i]['products'][j].isCheck = false;
          }
        }
      } else {
        // 全选
        for (var i in $scope.cartproducts) {
          for (var j in $scope.cartproducts[i]['products']) {
            // 选中添加
            $scope.goodschecked.push($scope.cartproducts[i]['products'][j]);
            $scope.cartproducts[i]['products'][j].isCheck = true;
          }
        }
      }
    })


    $scope.toPay = function() {
      if ($scope.goodschecked.length <= 0) {
        $rootScope.$broadcast('loading:showMessage', {
          message: '您还没有选中商品'
        });
        return;
      }
      // console.log(1);
      $rootScope.goodslist = $scope.goodschecked;
      $state.transitionTo('order.chooseloc', {}, {
        reload: true,
        inherit: false,
        notify: true
      });
    }

    // 选中goods
    $scope.setGoods = function(goods) {
      if (!$scope.edit) {
        goods.isCheck = !goods.isCheck;
        if (goods.isCheck) {
          $scope.goodschecked.push(goods);
        } else {
          var i = $scope.goodschecked.indexOf(goods);

          $scope.goodschecked.splice(i, 1);
        }
      }
    }

    // 设置 是否是编辑状态
    $scope.setEdit = function() {
      $scope.edit = !$scope.edit;
    }

    // 删除商品
    $scope.deleteGoods = function(goods) {
      UserService.deleteCart({
        value: goods.shopping_cart_id
      }).$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          // 从页面删除
          var key = goods.class3 + '_' + goods.sendtype;
          var i = $scope.cartproducts[key]['products'].indexOf(goods);
          $scope.cartproducts[key]['products'].splice(i, 1);
          //　删除类别
          if ($scope.cartproducts[key]['products'].length == 0) {
            // $scope.cartproducts.remove(key);
            delete $scope.cartproducts[key];
            // var j = $scope.cartproducts.indexOf($scope.cartproducts[key]);
            // $scope.cartproducts.splice(j, 1);
          }
        }
      })
    }

    $scope.goBack = function() {
      UtilsService.goBack();
    }

    if (UtilsService.isLogin()) {
      UserService.getCart().$promise.then(function(response) {
        if (UtilsService.isResponseOk(response)) {
          $scope.cartproducts = response.data.result;
          $scope.activity = response.data.activity;

          // 设置限购
          for (var i in $scope.cartproducts) {
            for (var j in $scope.cartproducts[i]['products']) {
              $scope.cartproducts[i]['products'][j].isCheck = true
              $scope.goodschecked.push($scope.cartproducts[i]['products'][j])
              var goods = $scope.cartproducts[i]['products'][j];
              if(goods.xg_amount && parseInt(goods.xg_amount) < goods.num){
                goods.num = parseInt(goods.xg_amount);
              }
            }
          }
        }
      });
    }
  });
